<?php
/**
 * 微信动作控制器
 *
 * @package    app
 * @version    1.0
 * @author     Ray 33705910@qq.com
 * @license    MIT License
 * @copyright  2013 - 2015 Ray
 * @link       http://wangxiaolei.cn
 */

/**
 * 本控制器主要用于：
 * 1.
 * @package  app
 * @extends  Controller
 */
namespace admin;

class Controller_WXAction extends Controller_BaseController {

	public $template = 'edu/template';

    public function action_index(){
    	$params = array(
  			'title' => '微信设置——关键字回复管理',
  			'menu' => ''
  		);

		$where = array();
		$params['items'] = \Model_WXAction::query()
			->related(array('material', 'material.items'))
			->where('keyword', 'NOT IN', array('subscribe', '*'))
			->get();

  		\View::set_global($params);
		$this->template->content = \View::forge("edu/wechat/items");
    }

    public function action_create(){
    	$params = array(
  			'title' => '微信设置——添加回复',
  			'menu' => ''
  		);

  		if(\Input::method() == 'POST'){
        $data = \Input::post();
  			$action = \Model_WXAction::forge($data);
        $action->material = \Model_WXMaterial::forge(array('msg_type' => 'text', 'account_id' => \Session::get('WXAccount')->id, 'enable' => 1, 'content' => $data['content']));
  			$action->save();
        $params['item'] = $action;
  		}else{
        if(in_array(\Input::get('type'), array('subscribe', '*'))){
          $action = \Model_WXAction::query()
                ->where('keyword', \Input::get('type'))
                ->where('account_id', \Session::get('WXAccount')->id)
                ->get_one();
          if( ! $action){
            $action = \Model_WXAction::forge(array('keyword' => 'subscribe', 'account_id' => \Session::get('WXAccount')->id, 'action_id' => 2, 'pattern' => '='));
            $action->material = \Model_WXMaterial::forge(array('msg_type' => 'text', 'account_id' => \Session::get('WXAccount')->id, 'enable' => 1));
            $action->save();
          }
          $params['item'] = $action;
        }
      }

    	

  		\View::set_global($params);
		$this->template->content = \View::forge("edu/wechat/details");
    }

    public function action_edit($id = 0){
    	$params = array(
  			'title' => '微信设置——编辑回复',
  			'menu' => ''
  		);

  		if(\Input::method() == 'POST'){
  			$data = \Input::post();
  			$action = \Model_WXAction::find($id);
  			$action->material->set($data);
  			$action->set($data);
  			$action->save();
  			$params['item'] = $action;
  		}

  		$params['item'] = \Model_WXAction::find($id);

  		\View::set_global($params);
		$this->template->content = \View::forge("edu/wechat/details");
    }
}